import java.awt.Window;
import java.io.File;
import java.lang.instrument.Instrumentation;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import sun.awt.AppContext;

//import com.logigear.ta.agent.diagnostic.AbtTrace;


public class JavaLoader {
		
	static final String JAVAAGENT_CLASS	= "com.agent.ReflectionMain" ;
	static final String ENV_TADEBUG_MODE	= "TADEBUG_MODE" ;
	static boolean shouldLog=hasLog();

	/*
	 * check if the system should log to console
	 */
	static private boolean hasLog(){
		String debugmode= System.getenv(ENV_TADEBUG_MODE);
		if(debugmode!=null &&debugmode.length()!=0){
			if(debugmode.equals("4")){
			return true;
			}
		}
		return false;
	}
	
	/***
	 * log message to debug
	 * @param message
	 */
	static private void log(String message){
		if(shouldLog){
			System.out.println(message);
		}
	}
	/*
	 * Aux : The JVM first attempts to invoke this method on the agent class
	 */
	public static void premain(String agentArgs, Instrumentation inst) {
		try
		{								 				
			File f = new File(JavaLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath());
			String appPath = f.getParent();
			
			String reflectionAppJar = appPath + java.io.File.separator + "ReflectionApp.jar" ;	
			
			// Load JavaAgent class
			URLClassLoader urlLoader = new URLClassLoader( new URL[]{new URL("file", null, reflectionAppJar)}) ;
			
		    Class<?> clsReflection = urlLoader.loadClass(JAVAAGENT_CLASS) ;
		    Object objJavaAgent = clsReflection.newInstance() ;
			if ( objJavaAgent != null )
			{
				System.out.println("[TAAgentLoader] Successfully loaded TAJavaAgent...") ;
			}
			else
			{
				System.out.println("[TAAgentLoader] Could not create a new instance of JavaAgent class.") ;
			}

		}
		catch ( ClassNotFoundException ex )
		{
			log("[TAAgentLoader] has exception ClassNotFoundException : " + ex.getMessage()) ;
		}
		catch(NoClassDefFoundError ex){
			log("[TAAgentLoader] has exception NoClassDefFoundError : " + ex.getMessage()) ;
		}
		catch (InstantiationException ex){
			log("[TAAgentLoader] has exception InstantiationException : " + ex.getMessage()) ;
		}
		catch ( Exception ex )
		{
			log("[TAAgentLoader] has exception Exception : " + ex.getMessage()) ;
		}		
	}
}